package com.iwdnb.gkgz.infrastructure.dao.repo.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.iwdnb.bmnf.common.utils.BeanConvertUtils;
import com.iwdnb.gkgz.common.model.dto.Stock;
import com.iwdnb.gkgz.common.model.dto.StockCandleDTO;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import com.iwdnb.gkgz.common.utils.CandleDataBuilder;
import com.iwdnb.gkgz.common.utils.RealtimeStockUtils;
import com.iwdnb.gkgz.common.utils.StockUtils;
import com.iwdnb.gkgz.infrastructure.dao.repo.StockRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import static com.iwdnb.gkgz.common.utils.DateUtils.afterOrEquals;
import static com.iwdnb.gkgz.common.utils.DateUtils.beforeOrEquals;

@Component
public class StockDayDataLocalRepositoryImpl extends StockDayDataRepositoryImpl {

    @Value("${gkgz.localFileDir}")
    private String localFileDir;
    @Autowired
    private StockRepository stockRepository;

    @Override
    public List<StockDayData> queryAll(String code) {
        StockCandleDTO stockCandleDTO = getStockCandle(code);
        if (Objects.isNull(stockCandleDTO)) {
            return null;
        }
        List<StockDayData> stockDayDataList = CandleDataBuilder.candleToDayData(stockCandleDTO.getCandleData());
        //实时更新今日数据
        String date = DateUtil.formatDate(new Date());
        StockDayData cacheTodayData = RealtimeStockUtils.getRealtimeData(code);
        if (Objects.nonNull(cacheTodayData)) {
            StockDayData todayData = StockUtils.getStockDayData(stockDayDataList, date);
            if (Objects.isNull(todayData)) {
                stockDayDataList.add(cacheTodayData);
            } else {
                BeanConvertUtils.copyProperties(cacheTodayData, todayData);
            }
        }
        for(StockDayData stockDayData:stockDayDataList){
            stockDayData.setCode(code);
        }
        StockUtils.calculateStockRange(stockDayDataList);
        return stockDayDataList;
    }

    @Override
    public List<StockDayData> queryAllByDateRange(String code, String startDate, String endDate) {
        List<StockDayData> stockDayDataList = queryAll(code);
        if (CollectionUtils.isEmpty(stockDayDataList)) {
            return null;
        }
        Date begin = DateUtil.parseDate(startDate);
        Date end = DateUtil.parseDate(endDate);
        return stockDayDataList.stream().filter(stockDayData -> {
            Date date = DateUtil.parseDate(stockDayData.getDate());
            return afterOrEquals(date, begin) && beforeOrEquals(date, end);
        }).collect(Collectors.toList());

    }

    @Override
    public void saveAll(String code, List<StockDayData> stockDayDataList) {
        StockUtils.sortStockDayDataList(stockDayDataList);
        StockUtils.calculateStockRange(stockDayDataList);
        String candleData = CandleDataBuilder.dayDataToCandle(stockDayDataList);
        StockCandleDTO stockCandleDTO = getStockCandle(code);
        if (Objects.isNull(stockCandleDTO)) {
            stockCandleDTO = new StockCandleDTO();
        }
        stockCandleDTO.setCode(code);
        stockCandleDTO.setCandleData(candleData);
        //String rangeData = JSON.toJSONString(StockRangeUtils.calculateStockRange(stockDayDataList));
        //stockCandleDTO.setRangeData(rangeData);
        String fullFileName = localFileDir + "stockCandle/" + code;
        FileUtil.writeUtf8String(JSON.toJSONString(stockCandleDTO), fullFileName);
    }

    private StockCandleDTO getStockCandle(String code) {
        String fullFileName = localFileDir + "stockCandle/" + code;
        if (!FileUtil.exist(fullFileName)) {
            FileUtil.touch(fullFileName);
            return null;
        }
        return JSON.parseObject(FileUtil.readUtf8String(fullFileName), StockCandleDTO.class);
    }

    public void initStockDayDataToLocal() {
        List<Stock> stockList = stockRepository.findAll();
        List<String> codes = stockList.stream()
            .map(stock -> stock.getCode()).collect(Collectors.toList());
        for (String code : codes) {
            List<StockDayData> list = super.queryAll(code);
            if (CollectionUtils.isEmpty(list)) {
                continue;
            }
            saveAll(code, list);
        }
    }
}
